package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.ArchivesBo;
import org.dromara.system.domain.bo.WbCompanyBidBagBO;
import org.dromara.system.domain.bo.WbCompanyInfoBo;
import org.dromara.system.domain.bo.WbOperatingProductsListBo;
import org.dromara.system.domain.dto.WbBidBagProductDTO;
import org.dromara.system.domain.dto.WbCompanyBidBagDTO;
import org.dromara.system.domain.dto.WbPlantEquipmentDTO;
import org.dromara.system.domain.vo.WbCompanyBlacklistVo;
import org.dromara.system.domain.vo.WbCompanyInfoVo;
import org.dromara.system.domain.vo.WbProductInfoVo;
import org.dromara.system.mapper.WbCompanyInfoMapper;
import org.dromara.system.mapper.WbCompanyProductListMapper;
import org.dromara.system.mapper.WbOperatingProductsListMapper;
import org.dromara.system.mapper.WbProductInfoMapper;
import org.dromara.system.service.IWbCompanyInfoService;
import org.dromara.system.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公司Service业务层处理
 *
 * @author Lion Li
 * @date 2024-03-22
 */
@RequiredArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class WbCompanyInfoServiceImpl implements IWbCompanyInfoService {

    private final WbCompanyInfoMapper baseMapper;

    private final WbProductInfoMapper wbProductInfoMapper;

    private final WbCompanyProductListMapper wbCompanyProductListMapper;

    private  final WbOperatingProductsListMapper wbOperatingProductsListMapper;


    /**
     * 查询公司
     */
    @Override
    public WbCompanyInfoVo queryById(Long id){
        return baseMapper.selectVoByIdZ(id);
    }

    /**
     * 查询公司列表 有分页
     */
    @Override
    public TableDataInfo<WbCompanyInfoVo> queryPageList(WbCompanyInfoBo bo,PageQuery pageQuery) {
        List<Long> companyIds = new ArrayList<>();
        LambdaQueryWrapper<WbCompanyInfo> lqw = buildQueryWrapper(bo);
        if(StringUtils.isNotBlank(bo.getProductName())){
            // 查询产品
            companyIds = wbOperatingProductsListMapper.selectCompanyIds(bo.getProductName());
            lqw.in(CollectionUtil.isNotEmpty(companyIds),WbCompanyInfo::getId,companyIds);
        }
        Page<WbCompanyInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<WbCompanyInfoVo> list = result.getRecords();
        for(WbCompanyInfoVo w : list){
            List<String> productNames = wbOperatingProductsListMapper.selectProductName(w.getId());
            w.setProductNames(productNames);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询公司列表
     */
    @Override
    public List<WbCompanyInfoVo> queryList(WbCompanyInfoBo bo) {
        LambdaQueryWrapper<WbCompanyInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WbCompanyInfo> buildQueryWrapper(WbCompanyInfoBo bo) {
        Map<String, Object> params = bo.getParams();

        LambdaQueryWrapper<WbCompanyInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, WbCompanyInfo::getId, bo.getId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), WbCompanyInfo::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getAbbreviation()), WbCompanyInfo::getAbbreviation, bo.getAbbreviation());
        lqw.eq(StringUtils.isNotBlank(bo.getRegistrationNumber()), WbCompanyInfo::getRegistrationNumber, bo.getRegistrationNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustry()), WbCompanyInfo::getIndustry, bo.getIndustry());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getFoundationDate()), WbCompanyInfo::getFoundationDate, bo.getFoundationDate());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getCapital()) , WbCompanyInfo::getCapital, bo.getCapital());
        lqw.eq(StringUtils.isNotBlank(bo.getLegalRepresentative()), WbCompanyInfo::getLegalRepresentative, bo.getLegalRepresentative());
        lqw.eq(StringUtils.isNotBlank(bo.getContactPerson()), WbCompanyInfo::getContactPerson, bo.getContactPerson());
        lqw.eq(StringUtils.isNotBlank(bo.getContactPhone()), WbCompanyInfo::getContactPhone, bo.getContactPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getContactEmail()), WbCompanyInfo::getContactEmail, bo.getContactEmail());
        lqw.like(StringUtils.isNotBlank(bo.getAddress()), WbCompanyInfo::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getWebsite()), WbCompanyInfo::getWebsite, bo.getWebsite());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getLogoUrl()), WbCompanyInfo::getLogoUrl, bo.getLogoUrl());
        lqw.eq(StringUtils.isNotEmpty(bo.getStatus()), WbCompanyInfo::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getBlackStatus()), WbCompanyInfo::getBlackStatus, bo.getBlackStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getSuggestStatus()), WbCompanyInfo::getSuggestStatus, bo.getSuggestStatus());

//        lqw.orderByDesc(WbCompanyInfo::getId);
//        lqw.ne( WbCompanyInfo::getStatus, "-1");
        return lqw;
    }

    /**
     * 新增公司
     */
    @Override
    public Boolean insertByBo(WbCompanyInfoBo bo) {
        WbCompanyInfo add = MapstructUtils.convert(bo, WbCompanyInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            Long id = add.getId();
            bo.setId(id);
            List<WbOperatingProductsList> list = new ArrayList<>();
            if (CollUtil.isNotEmpty(bo.getProductNames()) && flag){
                flag = false;
                for(String s : bo.getProductNames()){
                    WbOperatingProductsList opBo = new WbOperatingProductsList();
                    opBo.setCompanyId(bo.getId());
                    opBo.setProductName(s);
                    list.add(opBo);
                }
                boolean b = wbOperatingProductsListMapper.insertBatch(list);
                flag = b;
            }



        }
        return flag;
    }

    /**
     * 修改公司
     */
    @Override
    public Boolean updateByBo(WbCompanyInfoBo bo) {
        WbCompanyInfo update = MapstructUtils.convert(bo, WbCompanyInfo.class);
        validEntityBeforeSave(update);
        boolean b = baseMapper.updateById(update) > 0;
        if (CollUtil.isNotEmpty(bo.getProductNames()) && b){
            WbOperatingProductsList opBo = new WbOperatingProductsList();
            opBo.setCompanyId(bo.getId());
            Map<String,Object> map = new HashMap<>();
            map.put("company_id",bo.getId());
            int i = wbOperatingProductsListMapper.deleteByMap(map);
            List<WbOperatingProductsList> list = new ArrayList<>();
            for(String s : bo.getProductNames()){
                WbOperatingProductsList op = new WbOperatingProductsList();
                op.setCompanyId(bo.getId());
                op.setProductName(s);
                list.add(op);
            }
            boolean f = wbOperatingProductsListMapper.insertBatch(list);
            b = f;


        }
        return b;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WbCompanyInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除公司
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<WbCompanyBidBagDTO> queryMinBidBagList(WbCompanyBidBagBO bo, PageQuery pageQuery,int flag) {
        Page<WbCompanyBidBagDTO> listCompany;
        //flag=0左连接
        if (flag==0){
            if (bo.getProductName()!=null && bo.getProductName().equals("全部产品")){
                    bo.setProductName("");
            }
            listCompany = baseMapper.queryCompanyList(bo, pageQuery.build());

//            for(WbCompanyBidBagDTO q:listCompany.getRecords()){
//                List<String> productNames=baseMapper.queryCompanyProductNames(q.getId());
//                List<WbBidBagProductDTO> MinBidBag =baseMapper.queryBidBagProductList(q.getName(),bo);
//                q.setProductName(productNames);
//                q.setMinuteBidBagList(MinBidBag);
//            }
        }
        else{
            listCompany = baseMapper.queryCompanyListNotLeft(bo, pageQuery.build());
            for(WbCompanyBidBagDTO q:listCompany.getRecords()){
                List<WbBidBagProductDTO> MinBidBag =baseMapper.queryBidBagProductList(q.getName(),bo);
//                q.setMinuteBidBagList(MinBidBag);
            }
        }
        return TableDataInfo.build(listCompany);
    }

    @Override
    public TableDataInfo<WbMinuteBidBag> queryMinBidBagListOne(WbCompanyBidBagBO bo, PageQuery pageQuery) {
        Page<WbMinuteBidBag> MinBidBag =baseMapper.queryBidBagProductListOne(bo,pageQuery.build());
        return TableDataInfo.build(MinBidBag);
    }

    @Override
    public WbCompanyInfoVo queryByIdZdy(Long id) {
        return baseMapper.queryByIdZdy(id);
    }

    @Override
    public WbCompanyInfoVo queryDetailsById(Long id) {
        return baseMapper.queryDetailsById(id);
    }

    @Override
    public TableDataInfo<WbCompanyBidBagDTO> queryMinBidBagListZYT(String name,Long id, PageQuery pageQuery) {
        Page<WbCompanyBidBagDTO> companyBidBagDTOPage = baseMapper.selectVoPageZYT(name,id,pageQuery.build());
        return TableDataInfo.build(companyBidBagDTOPage);
    }

    @Override
    public TableDataInfo<WbCompanyInfoVo> queryPageList_xcx(WbCompanyInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WbCompanyInfo> lqw = buildQueryWrapper(bo);
        Page<WbCompanyInfoVo> result = baseMapper.queryPageList_xcx(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    @Override
    public WbCompanyInfoVo queryPageList_xcx_ZYT(Long enterpriseId) {
        return baseMapper.queryPageList_xcx_ZYT(enterpriseId);
    }

    @Override
    public TableDataInfo<Map> listMinBidBag1(WbCompanyInfoBo bo,Long provinceId, String itemName, String year ,PageQuery pageQuery) {
        LambdaQueryWrapper<WbCompanyInfo> lqw = buildQueryWrapper(bo);
        Page<Map> result = baseMapper.queryAllList_xcx_details(pageQuery.build(), provinceId, itemName, year, lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<WbCompanyInfoVo> queryPageListZ(WbCompanyInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WbCompanyInfo> lqw = buildQueryWrapper(bo);
        lqw.orderByAsc(WbCompanyInfo::getStatus);
        Page<WbCompanyInfoVo> page = baseMapper.selectVoPageZ(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    @Override
    public List<WbCompanyInfo> queryByName(String companyName) {
        return baseMapper.selectList(new LambdaQueryWrapper<WbCompanyInfo>()
            .eq(WbCompanyInfo::getName, companyName));
    }

    @Override
    public void handleName(String candidate) {
        if(StringUtils.isNotEmpty(candidate)){
            String regex = "\\d+"; // 匹配一个或多个数字字符
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher1 = pattern.matcher(candidate);
            if(!matcher1.find()){
                List<WbCompanyInfo> list = queryByName(candidate);
                if(list.size() == 0){
                    WbCompanyInfo wbCompanyInfo = new WbCompanyInfo();
                    wbCompanyInfo.setName(candidate);
                    wbCompanyInfo.setStatus("0");
                    baseMapper.insert(wbCompanyInfo);
                }
            }
        }
    }

    /**
     * 批量导入excel到数据库
     * @param bo
     * @param files
     * @return
     */
    @Override
    public R upload(WbCompanyInfoBo bo, MultipartFile[] files) {
        int num = 0;
        int err=0;
        for (MultipartFile file : files) {
            err++;
            try {
                //验证文件类型
                if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls") && !file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")) {
                    throw new Exception("文件类型有误！请上传Excel文件");
                }

                //获取公司信息数据

                List ttbZbzsList = new ArrayList<>();
                List<List<Object>> olist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "基本信息", "一般信息");
                //封装公司信息数据

                //根据下标获取每一行的每一条数据
                WbCompanyInfo wbCompanyInfo = new WbCompanyInfo();

                List<Object> list1 = olist.get(0);
                wbCompanyInfo.setName(String.valueOf(list1.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                List<Object> list2 = olist.get(1);
                wbCompanyInfo.setUnifiedSocialCreditCode(String.valueOf(list2.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                List<Object> list3 = olist.get(2);
                wbCompanyInfo.setLegalRepresentative(String.valueOf(list3.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                List<Object> list4 = olist.get(3);
                wbCompanyInfo.setCapital(String.valueOf(list4.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                List<Object> list5 = olist.get(4);
                wbCompanyInfo.setCurrency(String.valueOf(list5.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                List<Object> list6 = olist.get(5);
                wbCompanyInfo.setAddress(String.valueOf(list6.get(1)).replaceAll("\\s*|\r|\n|\t",""));

//                List<WbCompanyBlacklist> s = baseMapper.selectBlackRecod(String.valueOf(list1.get(1)));
//                if (s != null) {
//                    wbCompanyInfo.setBlackStatus("1");
//                } else wbCompanyInfo.setBlackStatus("0");
                ttbZbzsList.add(wbCompanyInfo);
                if (baseMapper.selectId(String.valueOf(list1.get(1))) == null) {
                    baseMapper.upload(ttbZbzsList);
                }

                Long companyId = baseMapper.selectId(String.valueOf(list1.get(1)));


                //获取报告证书数据
                {
                    List tbZbzsList = new ArrayList<>();
                    List<List<Object>> certlist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "报告证书", "管理体系认证证书");
                    //封装公司证书数据
                    if (!certlist.isEmpty()) {
                        for (List<Object> list : certlist) {
                            WbCompanyCert wbCompanyCert = new WbCompanyCert();

                            //根据下标获取每一行的每一条数据
                            wbCompanyCert.setCertificateId(String.valueOf(list.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                            wbCompanyCert.setCompanyId(companyId);
                            wbCompanyCert.setCompanyName(String.valueOf(list1.get(1)));

                            wbCompanyCert.setCertificateName(String.valueOf(list.get(2)).replaceAll("\\s*|\r|\n|\t",""));

                            wbCompanyCert.setCoverage(String.valueOf(list.get(3)).replaceAll("\\s*|\r|\n|\t",""));

                            wbCompanyCert.setCertifyingTime(String.valueOf(list.get(4)).replaceAll("\\s*|\r|\n|\t",""));

                            wbCompanyCert.setCertifyingEndTime(String.valueOf(list.get(5)).replaceAll("\\s*|\r|\n|\t",""));

                            wbCompanyCert.setCertifyingAgencies(String.valueOf(list.get(6)).replaceAll("\\s*|\r|\n|\t",""));

                            tbZbzsList.add(wbCompanyCert);
                        }
                        baseMapper.uploadWbCompanyCert(tbZbzsList);
                    }


                    //获取检验报告数据

                    List tstecertList = new ArrayList<>();
                    List<List<Object>> testcertlist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "报告证书", "检验报告");
                    //封装检验报告数据
                    if (!testcertlist.isEmpty()) {
                        for (List<Object> list : testcertlist) {
                            WbTestReport wbTestReport = new WbTestReport();

                            //根据下标获取每一行的每一条数据
                            wbTestReport.setMaterialRemark(String.valueOf(list.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                            wbTestReport.setCompanyId(companyId);
                            wbTestReport.setCompanyName(String.valueOf(list1.get(1)));

                            wbTestReport.setProductModel(String.valueOf(list.get(2)).replaceAll("\\s*|\r|\n|\t",""));

                            wbTestReport.setProductModel(String.valueOf(list.get(3)).replaceAll("\\s*|\r|\n|\t",""));

                            wbTestReport.setTestType(String.valueOf(list.get(4)).replaceAll("\\s*|\r|\n|\t",""));

                            wbTestReport.setTestReportIssuingAgency(String.valueOf(list.get(5)).replaceAll("\\s*|\r|\n|\t",""));

                            wbTestReport.setOtherReportIssuingAgency(String.valueOf(list.get(6)).replaceAll("\\s*|\r|\n|\t",""));

                            wbTestReport.setReportIssuingTime(String.valueOf(list.get(7)).replaceAll("\\s*|\r|\n|\t",""));

                            tstecertList.add(wbTestReport);
                        }
                        baseMapper.uploadWbTestReport(tstecertList);
                    }

                }


                {
                    List tstecertList = new ArrayList<>();
                    List<List<Object>> achilist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "产品业绩", "供货业绩");
                    //封装业绩数据
                    if (!achilist.isEmpty()) {
                        for (List<Object> list : achilist) {
                            if(list.size()<8){
                                continue;
                            }
                            WbProductAchievement wbProductAchievement = new WbProductAchievement();
                            //根据下标获取每一行的每一条数据
                            wbProductAchievement.setMaterialRemark(String.valueOf(list.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductAchievement.setCompanyId(companyId);
                            wbProductAchievement.setCompanyName(String.valueOf(list1.get(1)));

                            wbProductAchievement.setContractId(String.valueOf(list.get(2)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductAchievement.setItemName(String.valueOf(list.get(3)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductAchievement.setUnit(String.valueOf(list.get(4)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductAchievement.setContractStartTime(String.valueOf(list.get(5)).replaceAll("\\s*|\r|\n|\t",""));

                             wbProductAchievement.setActualSupplied(String.valueOf(list.get(6)).replaceAll("\\s*|\r|\n|\t",""));

                            String originalFilename = file.getOriginalFilename();
                            String substring = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                            String temp[] = substring.split("_");
                            String fileNameCC = temp[1];
                            String[] fileNameAll = fileNameCC.split("核");
                            String productName = fileNameAll[0];
                            wbProductAchievement.setProductName(productName);

//                                wbProductAchievement.setActualSupplied(null);


                            tstecertList.add(wbProductAchievement);
                        }
                        baseMapper.uploadProductAchievement(tstecertList);
                    }
                }

                {
                    List tstecertList = new ArrayList<>();
                    List<List<Object>> patentlist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "研发设计", "产品专利");
                    //封装专利数据
                    if (!patentlist.isEmpty()) {
                        for (List<Object> list : patentlist) {
                            WbProductPatent wbProductPatent = new WbProductPatent();

                            //根据下标获取每一行的每一条数据
                            wbProductPatent.setPatentType(String.valueOf(list.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductPatent.setCompanyId(companyId);
                            wbProductPatent.setCompanyName(String.valueOf(list1.get(1)));

                            wbProductPatent.setPatentName(String.valueOf(list.get(2)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductPatent.setPatentId(String.valueOf(list.get(3)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductPatent.setPatentee(String.valueOf(list.get(4)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductPatent.setLicensingNoticeTime(String.valueOf(list.get(5)).replaceAll("\\s*|\r|\n|\t",""));

                            tstecertList.add(wbProductPatent);
                        }
                        baseMapper.uploadProductPatent(tstecertList);
                    }
                }

                {
                    List tstecertList = new ArrayList<>();
                    List<List<Object>> plantlist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "生产制造", "生产厂房");
                    //封装厂房数据
                    if (!plantlist.isEmpty()) {
                        for (List<Object> list : plantlist) {
                            WbProductPlant wbProductPlant = new WbProductPlant();

                            //根据下标获取每一行的每一条数据
                            wbProductPlant.setProductPlantLocation(String.valueOf(list.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductPlant.setCompanyId(companyId);
                            wbProductPlant.setCompanyName(String.valueOf(list1.get(1)));

                            wbProductPlant.setProductPlantProperty(String.valueOf(list.get(2)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductPlant.setTotalArea(String.valueOf(list.get(3)).replaceAll("\\s*|\r|\n|\t",""));

                            tstecertList.add(wbProductPlant);

                        }
                        baseMapper.uploadProductPlant(tstecertList);
                    }

                    List tssbList = new ArrayList<>();
                    List<List<Object>> proequlist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "生产制造", "生产装备");
                    //封装生产设备数据
                    if (!proequlist.isEmpty()) {
                        for (List<Object> list : proequlist) {
                            WbProductEquipment wbProductEquipment = new WbProductEquipment();

                            //根据下标获取每一行的每一条数据
                            wbProductEquipment.setProductEquipmentName(String.valueOf(list.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductEquipment.setCompanyId(companyId);
                            wbProductEquipment.setCompanyName(String.valueOf(list1.get(1)));

                            wbProductEquipment.setProductEquipmentModel(String.valueOf(list.get(2)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductEquipment.setProductEquipmentNumber(String.valueOf(list.get(3)).replaceAll("\\s*|\r|\n|\t",""));

                            wbProductEquipment.setMainTechnicalParameter(String.valueOf(list.get(4)).replaceAll("\\s*|\r|\n|\t",""));

                            tssbList.add(wbProductEquipment);
                        }
                        baseMapper.uploadProductEquipment(tssbList);
                    }
                }

                {
                    List tstecertList = new ArrayList<>();
                    List<List<Object>> testequlist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "试验检测", "检测设备");
                    //封装检测设备数据
                    if (!testequlist.isEmpty()) {
                        for (List<Object> list : testequlist) {
                            WbTestEquipment wbTestEquipment = new WbTestEquipment();

                            //根据下标获取每一行的每一条数据
                            wbTestEquipment.setTestEquipmentName(String.valueOf(list.get(1)).replaceAll("\\s*|\r|\n|\t",""));

                            wbTestEquipment.setCompanyId(companyId);
                            wbTestEquipment.setCompanyName(String.valueOf(list1.get(1)));

                            wbTestEquipment.setTestEquipmentModel(String.valueOf(list.get(2)).replaceAll("\\s*|\r|\n|\t",""));

                            wbTestEquipment.setTestEquipmentNumber(String.valueOf(list.get(3)).replaceAll("\\s*|\r|\n|\t",""));

                            tstecertList.add(wbTestEquipment);
                        }
                        baseMapper.uploadTestEquipment(tstecertList);
                    }
                }

                {
                    List tstecertList = new ArrayList<>();
                    List<List<Object>> greenlist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "绿色低碳", "碳足迹");
                    //封装绿色低碳证书数据
                    if (!greenlist.isEmpty()) {
                        for (List<Object> list : greenlist) {
                            WbProductLowCarbonCert wbProductLowCarbonCert = new WbProductLowCarbonCert();

                            //根据下标获取每一行的每一条数据
                            wbProductLowCarbonCert.setCertId(String.valueOf(list.get(1)));

                            wbProductLowCarbonCert.setCompanyId(companyId);
                            wbProductLowCarbonCert.setCompanyName(String.valueOf(list1.get(1)));

                            wbProductLowCarbonCert.setProductCategoryName(String.valueOf(list.get(2)));

                            wbProductLowCarbonCert.setProductName(String.valueOf(list.get(3)));

                            wbProductLowCarbonCert.setProductModel(String.valueOf(list.get(4)));

                            wbProductLowCarbonCert.setCompanyName(String.valueOf(list.get(5)));

                            wbProductLowCarbonCert.setEvaluationAgency(String.valueOf(list.get(6)));

                            wbProductLowCarbonCert.setGreenhouseGasEmissionsPerFunctionalUnit(String.valueOf(list.get(7)));

                            wbProductLowCarbonCert.setIssueTime(String.valueOf(list.get(8)));

                            wbProductLowCarbonCert.setEndTime(String.valueOf(list.get(9)));

                            wbProductLowCarbonCert.setSupportingMaterialUrl(String.valueOf(list.get(10)));

                            tstecertList.add(wbProductLowCarbonCert);
                        }
                        baseMapper.uploadProductLowCarbonCert(tstecertList);
                    }
                }
                {
                    WbCompanyProductList wbProductInfo = new WbCompanyProductList();
                    String originalFilename = file.getOriginalFilename();
                    String substring = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                    String temp[] = substring.split("_");
                    String companyName = temp[0];
                    String fileNameCC = temp[1];
                    String[] fileNameAll = fileNameCC.split("核");
                    String productName = fileNameAll[0];
                    wbProductInfo.setCompanyId(String.valueOf(companyId));
                    wbProductInfo.setProductName(productName);
                    wbProductInfo.setCompanyName(companyName);
                    wbCompanyProductListMapper.insert(wbProductInfo);
                }
                num++;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.fail("第"+err+"条文件"+file.getOriginalFilename()+"数据出错了，请联系管理人员",e);
            }
        }
        return R.ok("导入成功数据数",num);
    }



    @Override
    public TableDataInfo<WbPlantEquipmentDTO> queryPlantEquipment(Long companyId, PageQuery pageQuery) {
        Page<WbPlantEquipmentDTO> wbPlantEquipmentDTOPage =baseMapper.queryPlantEquipment(companyId,pageQuery.build());
        for(WbPlantEquipmentDTO q:wbPlantEquipmentDTOPage.getRecords()){
            List<WbProductPlant> Plant =baseMapper.queryPlantEquipmentP(companyId,pageQuery.build());
            q.setWbProductPlant(Plant);
        }
        for(WbPlantEquipmentDTO q:wbPlantEquipmentDTOPage.getRecords()){
            List<WbProductEquipment> equipment =baseMapper.queryPlantEquipmentE(companyId,pageQuery.build());
            q.setWbProductEquipment(equipment);
        }

        return TableDataInfo.build(wbPlantEquipmentDTOPage);
    }

    @Override
    public void mergeDataByCandidate(String candidate) {
        ArchivesBo bo = new ArchivesBo();
            bo.setKeyword(candidate);
        List<WbCompanyInfo> voList = baseMapper.selectList(new LambdaQueryWrapper<WbCompanyInfo>().eq(true, WbCompanyInfo::getName, candidate));

        //如果为空或者没有更新天眼查数据
        if (!voList.isEmpty() && null != voList.get(0).getSkyId()) {//添加数据
            return;
        }

        WbCompanyInfo info = voList.isEmpty() ? null : voList.get(0);
        JSONObject data = SkyEyeClientUtil.query(bo, SkyEyeProperties.COMPANY_INFO);

        if(data != null && !data.isEmpty()) {
            baseMapper.insertOrUpdate(jsonToCompanyInfo(data, info));
        }
    }

    private WbCompanyInfo jsonToCompanyInfo(JSONObject data, WbCompanyInfo info) {
        if (info == null) {
            info = new WbCompanyInfo();
            info.setId(Long.parseLong(data.getStr("id")));
            info.setName(data.getStr("name"));
            info.setAddress(data.getStr("regLocation"));
            info.setRegistrationNumber(data.getStr("regNumber"));
            info.setStatus("0");
            info.setCapital(data.getStr("regCapital"));
            info.setBlackStatus("0");
            info.setBusinessModel(data.getStr("compForm"));
            info.setCurrency(data.getStr("regCapitalCurrency"));
            JSONObject jo = data.getJSONObject("industryAll");
            info.setIndustry(jo.isEmpty()?"":(jo.containsKey("categoryMiddle")?jo.getStr("categoryMiddle"):""));
            info.setDescription(data.getStr("businessScope"));
            info.setUnifiedSocialCreditCode(data.getStr("creditCode"));
            info.setRemark(data.getStr("tags"));
            info.setFoundationDate(DateUtil.date(data.getLong("estiblishTime")).toDateStr());
            info.setCreateBy(1L);
            info.setUpdateBy(1L);
            info.setCreateTime(new Date());
        }

        info.setSkyId(Long.parseLong(data.getStr("id")));
        info.setRegStatus(data.getStr("regStatus"));
        info.setLegalRepresentative(data.getStr("legalPersonName"));
        info.setContactEmail(data.getStr("email"));
        info.setWebsite(data.getStr("websiteList"));
        info.setContactPhone(data.getStr("phoneNumber"));
        info.setContactPerson(data.getStr("legalPersonName"));
        info.setUpdateBy(1L);
        info.setUpdateTime(new Date());

        return info;
    }
}
